package com.haitaoit.chengquan.module.car.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.bean.CheckBeen;
import com.haitaoit.chengquan.module.car.adapter.OrderSubmitAdapter;
import com.haitaoit.chengquan.module.car.model.OrderSubmitModel;
import com.haitaoit.chengquan.module.center.activity.info.MyAddressActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.MyListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class OrderSubmitActivity extends BaseActivity {
    @ViewInject(R.id.order_addresstv)
    TextView     order_addresstv;
    @ViewInject(R.id.order_addressll)
    LinearLayout order_addressll;
    @ViewInject(R.id.order_address_name)
    TextView     order_address_name;
    @ViewInject(R.id.order_address_phone)
    TextView     order_address_phone;
    @ViewInject(R.id.order_address_title)
    TextView     order_address_title;
    @ViewInject(R.id.scrollview_listview)
    MyListView   listView;
    @ViewInject(R.id.order_kuaidi)
    TextView     order_kuaidi;
    @ViewInject(R.id.order_money)
    TextView     order_money;
    @ViewInject(R.id.order_all_money)
    TextView     order_all_money;
    @ViewInject(R.id.order_coupon)
    TextView     order_coupon;
    @ViewInject(R.id.dikou)
    TextView     dikou;
    @ViewInject(R.id.order_message)
    EditText     order_message;
    @ViewInject(R.id.invoice_looked_up)
    EditText     invoice_looked_up;
    @ViewInject(R.id.shop_point_dikou)
    LinearLayout shop_point_dikou;
    @ViewInject(R.id.checkbox)
    CheckBox     checkbox;


    private OrderSubmitAdapter adapter;
    private String car_id = "0", product_id = "0", specid = "0", count = "0", coupons_id = "0";
    private OrderSubmitModel model;

    private String is_deduction = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_order_submit);
        setTitle_V("确认订单");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);


        adapter = new OrderSubmitAdapter(this);
        listView.setAdapter(adapter);

        if (getIntent().getStringExtra("type").equals("now")) {// 立即购买
            product_id = getIntent().getStringExtra("product_id");
            specid = getIntent().getStringExtra("specid");
            count = getIntent().getStringExtra("count");
        } else if (getIntent().getStringExtra("type").equals("car")) {// 购物车
            car_id = getIntent().getStringExtra("id");
        }
    }

    @Override
    protected void onResume() {
        if (hasNetWork()) {
            httpGetconfirm_order_list();
             makeIsDeduction();
        }
        super.onResume();
    }

    //TODO：这里虽然是随机数，但是最好是产品的Id，针对特别的物品进行特别的打折
    private void makeIsDeduction() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("rnd", product_id);
        final String sign = GetSign.getSign(map);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .get()
                        .url(Constant.GETPOINTS_CASH)
                        .addParams("rnd", product_id)
                        .addParams("sign", sign)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastUtils.showToast("请求失败");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                Gson gson = new Gson();
                                CheckBeen been = gson.fromJson(response, CheckBeen.class);
                                if (been == null) {
                                    ToastUtils.showToast("请求失败");
                                    return;
                                }
                                if (!TextUtils.equals(been.getErrCode(), "0")) {
                                    ToastUtils.showToast(been.getErrMsg());
                                    return;
                                }
                                if (TextUtils.equals(been.getErrCode(), "0")) {
                                    final String money = been.getResponse().getShop_amount();
                                    final String amount = been.getResponse().getShop_point();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (TextUtils.equals("0", money) || TextUtils.equals("0", amount)) {
                                                //如果有积分抵扣活动就显示，若没有就不显示
                                                shop_point_dikou.setVisibility(View.GONE);
                                            } else {
                                                dikou.setText("使用" + amount + "积分抵扣" + money + "元");
                                            }
                                        }
                                    });
                                }
                            }
                        });
            }
        }).start();


    }

    @OnClick({R.id.address_ll, R.id.order_couponLL, R.id.order_submit,R.id.order_addresstv})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.address_ll:// 地址
                intent.setClass(this, MyAddressActivity.class);
                startActivity(intent);
                break;
            case R.id.order_couponLL:// 优惠券
                intent.setClass(this, CouponActivity.class);
                intent.putExtra("coupon", (Serializable) model.getCoupons_list());
                startActivityForResult(intent, 11);
                break;
            case R.id.order_submit:// 提交
                if (model.getAddress_model() == null) {
                    ToastUtils.showToast("请选择收货地址！");
                } else {
                    if (hasNetWork()) {
                        if (checkbox.isChecked()) {
                            is_deduction = "2";
                        } else {
                            is_deduction = "1";
                        }
                        httpGetadd_order_list();
                    }
                }
                break;
            case R.id.order_addresstv:
                intent.setClass(this, MyAddressActivity.class);
                startActivity(intent);
                break;
        }
        super.onClick(v);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 11 && resultCode == 11) {
            coupons_id = model.getCoupons_list().get(Integer.valueOf(data.getStringExtra("position"))).getId();
            order_coupon.setText(model.getCoupons_list().get(Integer.valueOf(data.getStringExtra("position"))).getMoney());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void httpGetconfirm_order_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("cart_id", car_id));
        list.add(new NameValuePairSign("goods_id", product_id));
        list.add(new NameValuePairSign("goods_specifications_id", specid));
        list.add(new NameValuePairSign("goods_specifications_count", count));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("cart_id", car_id);
        params.addQueryStringParameter("goods_id", product_id);
        params.addQueryStringParameter("goods_specifications_id", specid);
        params.addQueryStringParameter("goods_specifications_count", count);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getconfirm_order_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            model = gson.fromJson(Response, OrderSubmitModel.class);

                            if (model.getAddress_model() == null) {
                                order_addresstv.setVisibility(View.VISIBLE);
                                order_addressll.setVisibility(View.GONE);
                            } else {
                                order_addresstv.setVisibility(View.GONE);
                                order_addressll.setVisibility(View.VISIBLE);

                                order_address_name.setText("收货人：" + model.getAddress_model().getName());
                                order_address_phone.setText(model.getAddress_model().getPhone());
                                order_address_title.setText("收货地址：" + model.getAddress_model().getAddress());
                            }

                            adapter.setList(model.getCart_list());
                            adapter.notifyDataSetChanged();

                            if (model.getFreight_amount().equals("0")) {
                                order_kuaidi.setText("免运费");
                            } else {
                                order_kuaidi.setText("¥ " + model.getFreight_amount());
                            }
                            order_money.setText("¥ " + model.getOrder_amount());
                            if (order_coupon.getText().toString().equals("")) {
                                order_all_money.setText("¥ " + model.getOrder_amount());
                            } else {
                                order_all_money.setText("¥ " + Utils.format((Float.valueOf(model.getOrder_amount()) -
                                        Float.valueOf(order_coupon.getText().toString()))));
                            }
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 提交生成订单
    private void httpGetadd_order_list() {

        //还需要积分兑换成金钱
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("address_id", model.getAddress_model().getId()));
        list.add(new NameValuePairSign("cart_id", car_id));
        list.add(new NameValuePairSign("goods_id", product_id));
        list.add(new NameValuePairSign("goods_specifications_id", specid));
        list.add(new NameValuePairSign("goods_specifications_count", count));
        list.add(new NameValuePairSign("user_remark", order_message.getText().toString()));
        list.add(new NameValuePairSign("invoice_looked_up", invoice_looked_up.getText().toString()));
        list.add(new NameValuePairSign("coupons_id", coupons_id));
        list.add(new NameValuePairSign("is_deduction", is_deduction));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("address_id", model.getAddress_model().getId());
        params.addQueryStringParameter("cart_id", car_id);
        params.addQueryStringParameter("goods_id", product_id);
        params.addQueryStringParameter("goods_specifications_id", specid);
        params.addQueryStringParameter("goods_specifications_count", count);
        params.addQueryStringParameter("user_remark", order_message.getText().toString());
        params.addQueryStringParameter("invoice_looked_up", invoice_looked_up.getText().toString());
        params.addQueryStringParameter("coupons_id", coupons_id);
        params.addQueryStringParameter("is_deduction", is_deduction);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getadd_order_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            Intent intent = new Intent(OrderSubmitActivity.this, OrderPayActivity.class);
                            intent.putExtra("order_no", js.getString("order_no"));
                            intent.putExtra("order_amount", js.getString("order_amount"));
                            startActivity(intent);
                            finish();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

}
